#include "drscontrol.h"
#include <QTimer>
#include "qextserialport.h"

void DRSControl::createSerialPort()
{
	qDebug() << "createSerialPort";
}
void DRSControl::on_serialMessageLineEdit_returnPressed(void)
{
	transmitMsg();
	ui.serialMessageLineEdit->clear();
}
void DRSControl::on_openPortPushButton_clicked(bool clicked)
{
	QString str = ui.openPortPushButton->text();
	int x = str.compare("Open Port");
	if(x == 0)
	{
		qDebug() << "clicked";
		port = new QextSerialPort();
		port->setPortName(ui.portComboBox->currentText());
		port->setDataBits(DATA_8);
		port->setParity(PAR_NONE);
		port->setFlowControl(FLOW_HARDWARE);
		port->setStopBits(STOP_1);
		port->setBaudRate(DRSControl::getBuadRate());
		port->open();
		connect(ui.serialSendPushButton,SIGNAL(clicked()),SLOT(transmitMsg()));
		ui.openPortPushButton->setText("Close Port");
	}
	else
	{
		port->close();
		//delete port;
		ui.openPortPushButton->setText("Open Port");
	}

}
void DRSControl::transmitMsg()
{
	int i = port->writeData(
		(ui.serialMessageLineEdit->text()+"\x0D\x0A").toAscii(),
		(ui.serialMessageLineEdit->text()+"\x0D\x0A").length());
	QString m = ui.serialMessageLineEdit->displayText();
	m = m.prepend("TX: ");
	ui.recievedTextEdit->append(m);
	qDebug() << "trasmitted : " << i;
	QTimer *receiveTimer = new QTimer(this);
	connect(receiveTimer, SIGNAL(timeout()), SLOT(receiveMsg()));
	receiveTimer->start(70);
}

void DRSControl::receiveMsg()
{
  int numBytes = port->bytesAvailable();

	if(numBytes > 0) 
	{
		qDebug() << "numBytes availible=" << numBytes;
		char buff[255];                         // Give a buffer to fill
		int i = port->readData(buff, numBytes); //read the data off the port.
		buff[numBytes] = '\0';                  // finish it off with a null.
		QString msg = buff;                     // do the QT magic to display it.
		qDebug() << "msg=" << msg;
		msg = msg.remove("\r\n",Qt::CaseInsensitive);
		msg = msg.prepend("RX: ");
		ui.recievedTextEdit->append(msg);       // append it to the textEdit feild to display.
		qDebug() << "received : " << i;
	}
}
BaudRateType DRSControl::getBuadRate()
{
	BaudRateType x;
	int i = ui.baudRateComboBox->currentIndex();
	switch(i)
	{
		case 0:
			x = BAUD9600;
			break;
		case 1:
			x = BAUD115200;
			break;
		default:
			x = BAUD9600;
			break;
	}
	return x;
}
void DRSControl::on_serialClearPushButton_clicked(bool clicked)
{
	ui.recievedTextEdit->clear();
}